<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('融资轮次')" prop="financingRound">
            <el-select v-model="form.financingRound" filterable :placeholder="$t('融资轮次')">
              <el-option
                v-for="dict in financingRoundOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资方式')" prop="financingMode">
            <el-select v-model="form.financingMode" filterable :placeholder="$t('融资方式')">
              <el-option
                v-for="dict in financingModeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资日期')" prop="financingDate">
            <el-date-picker
              v-model="form.financingDate"
              clearable
              style="width: 200px"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('融资日期')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资总金额')" prop="financingTotal">
            <Money v-model="form.financingTotal" unit="w" disabled :placeholder="$t('融资总金额')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('注册资本/总股本')" prop="registerCapital">
            <Money v-model="form.registerCapital" unit="w" :placeholder="$t('注册资本/总股本')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资前估值')" prop="preFinancingVal">
            <Money v-model="form.preFinancingVal" unit="w" :placeholder="$t('融资前估值')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('融资后估值') + $t('金额单位')" prop="postFinancingVal">
            <Money v-model="form.postFinancingVal" unit="w" :placeholder="$t('融资后估值')" />
          </el-form-item>
        </el-col>
      </el-row>
      <!--出资机构列表-->
      <div style="margin-top:15px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('出资机构列表') }}</span>
        </div>
        <el-table
          :data="form.companyInvestmentOrganList"
          border
          class="nowrapTable formTable tree_el_Table"
          :summary-method="getInvestmentAmounts"
          show-summary
        >
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('机构名称')" align="center" prop="mechanismName">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('机构名称') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'companyInvestmentOrganList.' + scope.$index + '.mechanismName'" :rules="companyInvestmentOrganListRules.mechanismName">
                <el-input v-model="scope.row.mechanismName" :placeholder="$t('机构名称')" show-word-limit maxlenth="100" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('投资金额') + $t('金额单位')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('投资金额') }}{{ $t('金额单位') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'companyInvestmentOrganList.' + scope.$index + '.investmentAmount'" :rules="companyInvestmentOrganListRules.investmentAmount">
                <Money v-model="scope.row.investmentAmount" unit="w" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('持股数量')" align="center">
            <template slot="header" slot-scope="{}">
              <span>{{ $t('持股数量') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'companyInvestmentOrganList.' + scope.$index + '.shareholdNum'">
                <Money v-model="scope.row.shareholdNum" :placeholder="$t('持股数量')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('持股比例')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('持股比例') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'companyInvestmentOrganList.' + scope.$index + '.shareholdRatio'" :rules="companyInvestmentOrganListRules.shareholdRatio">
                <el-input-number v-model="scope.row.shareholdRatio" :placeholder="$t('持股比例(%)')" :controls="false" :min="0" :max="100" :precision="2" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center" prop="remark">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark" :placeholder="$t('备注')" show-word-limit maxlenth="200" />
            </template>
          </el-table-column>
          <el-table-column :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['company:financeHistory:remove']" type="text" icon="el-icon-delete" @click="delHandleTerms(scope.$index, scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <div class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addInvestmentOrgan">{{ $t("添加") }}</el-button>
        </div>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存 取消按钮-->
      <save-btn has-permi="company:financeHistory" />
    </div>
  </div>
</template>

<script>
    import { saveCompanyFinancingHistory, getCompanyFinancingHistory, delCompanyInvestmentOrgan } from '@/api/company/financeHistory/companyFinancingHistory'
    export default {
        data() {
            return {
                financingModeOptions: [],
                financingRoundOptions: [],
                // 表单参数
                form: {
                  companyInvestmentOrganList: []
                },
                // 遮罩层
                loading: false,
                // 表单校验
                rules: {
                  financingRound: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  financingMode: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  financingDate: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  financingTotal: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  registerCapital: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  postFinancingVal: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                companyInvestmentOrganListRules: {
                  mechanismName: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  investmentAmount: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  shareholdRatio: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                }
            }
        },
        created() {
          this.getDicts('financing_mode').then(response => {
            this.financingModeOptions = response.data
          })
          this.getDicts('rounds_investment').then(response => {
            this.financingRoundOptions = response.data
          })
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                    getCompanyFinancingHistory(data.id).then(response => {
                        this.form = response.data
                        this.loading = false
                    })
                } else {
                    this.reset()
                    this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                    id: undefined,
                    companyId: this.$route.query.companyId,
                    financingRound: undefined,
                    financingMode: undefined,
                    financingDate: undefined,
                    financingTotal: undefined,
                    registerCapital: undefined,
                    preFinancingVal: undefined,
                    postFinancingVal: undefined,
                    remark: undefined,
                    createBy: undefined,
                    createTime: undefined,
                    updateBy: undefined,
                    updateTime: undefined,
                    delFlag: undefined,
                    companyInvestmentOrganList: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 添加投资组合信息
            addInvestmentOrgan() {
              const row = {
                id: undefined,
                companyId: this.$route.query.companyId,
                mechanismName: '',
                investmentAmount: '',
                shareholdNum: '',
                shareholdRatio: '',
                remark: ''
              }
              if (!(this.form.companyInvestmentOrganList instanceof Array)) {
                this.$set(this.form, 'companyInvestmentOrganList', [])
              }
              this.$nextTick(() => {
                this.form.companyInvestmentOrganList.push(row)
              })
            },
            // 删除投资机构列表中选中的数据
            delHandleTerms(index, row) {
              // eslint-disable-next-line no-undef
              const id = row.id
              if (id !== undefined && id !== '' && id != null) {
                this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                  confirmButtonText: this.$t('确定'),
                  cancelButtonText: this.$t('取消'),
                  type: 'warning'
                })
                  .then(function() {
                    return delCompanyInvestmentOrgan(id)
                  }).then(() => {
                  this.form.companyInvestmentOrganList.splice(index, 1)
                  return this.msgSuccess(this.$t('删除成功'))
                })
                  .catch(function() {})
              } else {
                this.form.companyInvestmentOrganList.splice(index, 1)
              }
            },
            // 计算报销总额
            getInvestmentAmounts() {
              let sum = 0
              let totalRadio = 0
              if (this.form.companyInvestmentOrganList !== null && this.form.companyInvestmentOrganList !== undefined && this.form.companyInvestmentOrganList.length > 0) {
                this.form.companyInvestmentOrganList.forEach(item => {
                  if (item.investmentAmount !== undefined && item.investmentAmount !== null && item.investmentAmount !== '') {
                    sum += +item.investmentAmount
                  }
                  if (item.shareholdRatio !== undefined && item.shareholdRatio !== null && item.shareholdRatio !== '') {
                    totalRadio += +item.shareholdRatio
                  }
                })
                this.$set(this.form, 'financingTotal', sum)
                if (totalRadio !== 0) {
                  this.form.postFinancingVal = parseFloat(sum / (totalRadio / 100))
                } else {
                  this.form.postFinancingVal = ''
                }
              }
              return sum
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                if (this.$parent.$parent.formOpen !== undefined) {
                  this.$parent.$parent.formOpen = false
                }
                // 刷新list页面
                if (this.$parent.$parent.getList !== undefined) {
                  this.$parent.$parent.getList()
                }
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        saveCompanyFinancingHistory(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        })
                    } else {
                      this.locationError(document)
                    }
                })
           }

        }

    }
</script>
